﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Infrastructure.Tool
{
    public class Generator
    {

        private static DateTime unixStartTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

        public static bool CurrentAccountIsSpecial()
        {
            dynamic sessionUser = HttpContext.Current.Session["UserInfo"];
            return sessionUser != null && sessionUser.IsSpecialAccount != null && sessionUser.IsSpecialAccount;
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (strContent.IndexOf(strSplit) < 0)
            {
                string[] tmp = { strContent };
                return tmp;
            }
            return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, int p_3)
        {
            string[] result = new string[p_3];

            string[] splited = SplitString(strContent, strSplit);

            for (int i = 0; i < p_3; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }


        public static DateTime StampToDateTime(string timeStamp)
        {
            for (int i = timeStamp.Length; i < 17; i++)
            {
                timeStamp += "0";
            }
            TimeSpan stamp = new TimeSpan(long.Parse(timeStamp));
            return unixStartTime.Add(stamp);
        }

        public static int DateTimeToStamp(DateTime dateTime)
        {
            TimeSpan stamp = dateTime - unixStartTime;
            return (int)stamp.TotalSeconds;
        }

        public static string PasswordSalt()
        {
            StringBuilder builder = new StringBuilder();
            char[] chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToArray();
            for (int i = 0; i < 8; i++)
            {
                builder.Append(chars[NextRandom(chars.Length - 1)]);
            }
            return builder.ToString();
        }


        /// <summary>
        /// 获取随机密码
        /// </summary>
        /// <param name="charString">混淆字符串</param>
        /// <param name="count">返回密码位数</param>
        /// <returns></returns>
        public static string GetRandomPassword(string charString, int count)
        {
            StringBuilder builder = new StringBuilder();
            char[] chars = charString.ToArray();
            for (int i = 0; i < count; i++)
            {
                builder.Append(chars[NextRandom(chars.Length - 1)]);
            }
            return builder.ToString();
        }

        /// <summary>
        /// 使用CSPRNG生成强随机数
        /// </summary>
        /// <param name="max">随机数的最大值</param>
        /// <returns>返回一个随机数</returns>
        public static int NextRandom(int max)
        {
            byte[] randomByte = new byte[4];
            var gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
            gen.GetBytes(randomByte);
            int value = BitConverter.ToInt32(randomByte, 0);
            value = value % (max + 1);
            if (value < 0) value = -value;
            return value;
        }

        /// <summary>
        /// MD5加密方法
        /// </summary>
        /// <param name="value">需要加密的值</param>
        /// <param name="salt">加密盐值，默认不加盐</param>
        /// <returns>返回MD5加密值</returns>
        public static string MD5(string value, string salt = "")
        {
            byte[] result = Encoding.Default.GetBytes(value + salt);
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToUpper();
        }



        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (string.IsNullOrEmpty(result) || !IsIP(result))
            {
                return "0.0.0.0";
            }

            return result;

        }

        /// <summary>
        /// IP检测
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsIP(string input)
        {
            return (!string.IsNullOrEmpty(input) && Regex.IsMatch(input.Trim(), @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"));
        }


        public static string DoGetHostAddresses(string hostname)
        {
            try
            {
                IPAddress[] ips;
                ips = Dns.GetHostAddresses(hostname);
                return ips[0].ToString();
            }
            catch (Exception)
            {

                return hostname;
            }
        }

        /// <summary>
        /// 掩埋字符串的中间内容
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncName(string str)
        {
            str = str.Trim();
            if (str.Length < 1)
            {
                return "***";
            }
            else if (str.Length < 2)
            {
                return str.Substring(0, 1) + "***";
            }
            return str.Substring(0, 1) + "***" + str.Substring(str.Length - 1, 1);
        }

        /// <summary>
        /// 过滤字符串
        /// </summary>
        /// <returns></returns>
        public static string GetSafeString(object str)
        {
            if (str == null)
            {
                return string.Empty;
            }

            string text = str.ToString().Trim();
            if (text == string.Empty)
            {
                return string.Empty;
            }

            text = Regex.Replace(text, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);	//any other tags+
            text = text.Replace("'", "''");
            return text;
        }
        /// <summary>
        /// 获取url中get参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetQueryString(string key)
        {
            return Generator.GetSafeString(System.Web.HttpContext.Current.Request.QueryString[key]);
        }


        /// <summary>
        /// 获取表单的值
        /// </summary>
        /// <param name="key">表单的key</param>
        /// <returns></returns>
        public static string GetFormValue(string key)
        {
            return GetFormValue(key, Int32.MaxValue);
        }
        /// <summary>
        /// 获取表单的值
        /// </summary>
        /// <param name="key">表单的key</param>
        /// <param name="maxLength">接受的最大长度</param>
        /// <returns></returns>
        public static string GetFormValue(string key, int maxLength)
        {
            string tmp = HttpContext.Current.Request.Form[key] != null ? HttpContext.Current.Request.Form[key].ToString() : "";
            return GetSafeString(tmp);
        }

        /// <summary>
        /// 获取get或者post值
        /// </summary>
        /// <param name="key">表单的key</param>
        /// <param name="maxLength">接受的最大长度</param>
        /// <returns></returns>
        public static string GetParamsValue(string key)
        {
            string tmp = GetFormValue(key);
            if (string.IsNullOrEmpty(tmp))
            {
                tmp = GetQueryString(key);
            }
            return GetSafeString(tmp);
        }

        public static string[] GetFormValues(string key)
        {
            string[] tmps = HttpContext.Current.Request.Form.GetValues(key);
            if (tmps == null)
            {
                return new string[] { };
            }
            for (int i = 0; i < tmps.Length; i++)
            {
                tmps[i] = GetSafeString(tmps[i]);
            }
            return tmps;
        }

        public static decimal GetDisPrice(decimal price, int discount)
        {
            if (discount > 0)
            {
                return decimal.Parse((price * discount * (decimal)0.01).ToString("0.00"));
            }
            else
            {
                return price;
            }
        }

        #region String转Guid
        public static bool IsGuidByParse(string strSrc)
        {
            Guid g = Guid.Empty;
            return Guid.TryParse(strSrc, out g);
        }
        #endregion

        #region 获取网站domain
        public static string DomainUrl
        {
            get { return "http://" + HttpContext.Current.Request.Url.Host; }
        }
        #endregion

        #region Cookie设置

        /// <summary>
        /// 设置cookie
        /// </summary>
        public static void SetCookie(string key, string value)
        {
            HttpContext.Current.Response.Cookies.Remove(key);
            HttpContext.Current.Response.Cookies[key].Expires = DateTime.Now.AddDays(-1);

            //Add Cookie.
            //LongTimeUserName_Cookie.
            HttpCookie cookies = new HttpCookie(key);
            cookies.Value = HttpUtility.UrlEncode(value, System.Text.Encoding.UTF8);
            HttpContext.Current.Response.AppendCookie(cookies);

        }

        public static void ClearCookie(string key)
        {
            HttpContext.Current.Response.Cookies.Remove(key);
            HttpContext.Current.Response.Cookies[key].Expires = DateTime.Now.AddDays(-1);
        }
        /// <summary>
        /// 设置cookie
        /// </summary>
        public static string GetCookie(string key)
        {
            HttpCookie cookies = HttpContext.Current.Request.Cookies[key];
            if (cookies != null)
            {
                return cookies.Value;
            }
            else
            {
                return "";

            }
        }

        #endregion

        #region 时间戳转换
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name=”time”></param>
        /// <returns></returns>
        public static int ConvertDateTimeInt(DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        #endregion
    }
}
